package org.tlang.ast;

import org.tlang.context.SymbolTable;
import org.tlang.context.TypeTable;
import org.tlang.exception.TypeException;
import org.tlang.type.Type;
import org.tlang.type.VoidType;

import java.util.ArrayList;
import java.util.List;

public class ASTList extends AST {
    private final List<AST> children;

    public ASTList(List<AST> children) {
        this.children = children == null ? new ArrayList<>() : children;
    }

    @Override
    public AST child(int i) {
        return children.get(i);
    }

    @Override
    public int numChildren() {
        return children.size();
    }

    @Override
    public List<AST> children() {
        return children;
    }

    @Override
    public String location() {
        for (AST ast : children) {
            String str = ast.location();
            if (str != null) {
                return str;
            }
        }
        return null;
    }

    @Override
    public void lookup(SymbolTable symbolTable, TypeTable typeTable) {
        for (AST ast : children) {
            ast.lookup(symbolTable, typeTable);
        }
    }

    @Override
    public Type typeCheck(TypeTable typeTable) throws TypeException {
        for (AST ast : children) {
            ast.typeCheck(typeTable);
        }
        return VoidType.VOID_TYPE;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(");
        String sep = "";
        for (AST ast : children) {
            stringBuilder.append(sep);
            sep = toStringSep();
            stringBuilder.append(ast.toString());
        }
        return stringBuilder.append(")").toString();
    }

    protected String toStringSep() {
        return " ";
    }
}
